﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace Web.ashx
{
    /// <summary>
    /// ajax 的摘要说明
    /// </summary>
    public class ajax : Evan.WebUI.BaseAshx
    {
        public override void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";

            //获取action
            string action = context.Request.Form["action"];
            action = action ?? context.Request["action"];

            switch (action)
            {
                //在线留言
                case "OnlineMessage":
                    OnlineMessage(context);
                    break;
                case "Message":
                    Message(context);
                    break;
                case "bondtrading":
                    GetBond(context);
                    break;
                case "exportexcel":
                    ExportExcel(context);
                    break;
                case "CheckFormByAboutJob":
                    CheckFormByAboutJob(context);
                    break;
                default:
                    context.Response.Redirect("/errorpage/404.aspx");
                    break;
            }


        }

        private void ExportExcel(HttpContext context)
        {
            int ClassId = int.Parse(context.Request["ClassId"]);
            int curPage = 0;
            string WhereStr = "";

            //string _temp_curpage = GetParam("curPage");
            //if (!string.IsNullOrEmpty(_temp_curpage))
            //{
            //    curPage = int.Parse(_temp_curpage);
            //}
            //string _temp_title = GetParam("title");
            //if (!string.IsNullOrEmpty(_temp_title))
            //{
            //    //暂时只支持按照标题搜索的结果
            //    WhereStr = string.Format("Title like '%{0}%'", _temp_title);
            //}
            Evan.Common.ExportExcel.ExportData(ClassId, curPage, WhereStr);
        }



        private void GetBond(HttpContext context)
        {
            JObject res = new JObject();
            try
            {
                string curpage = context.Request["curpage"];
                string curPageSize = context.Request["curPageSize"];


                if (!Evan.Common.Utils.IsSafeSqlString(curpage))
                {
                    res["States"] = false;
                    res["Msg"] = "关键词包含特殊字符，请重新输入！";
                    JsonResult(context, res);
                }
                curpage = Evan.Common.Utils.FiterHtmls(curpage);
                if (!string.IsNullOrEmpty(curpage))
                {
                    if (sql_inj(curpage.ToLower()))
                    {
                        HttpContext.Current.Response.Redirect("/ErrorPage/404.aspx");
                    }
                }

                if (!Evan.Common.Utils.IsSafeSqlString(curPageSize))
                {
                    res["States"] = false;
                    res["Msg"] = "关键词包含特殊字符，请重新输入！";
                    JsonResult(context, res);
                }
                curPageSize = Evan.Common.Utils.FiterHtmls(curPageSize);
                if (!string.IsNullOrEmpty(curPageSize))
                {
                    if (sql_inj(curPageSize.ToLower()))
                    {
                        HttpContext.Current.Response.Redirect("/ErrorPage/404.aspx");
                    }
                }





                dynamic form = context.Request.Form;//获取前台表单对象
                string where = " states=1 and ClassId=118 ";
                Evan.DataBase.DbOperat dbOperat = new Evan.DataBase.DbOperat("Faq");


                var num = 0;
                foreach (var item in form)
                {

                    if (num == 0)
                    {
                        where += " and (";
                    }

                    string[] str = form[item].Split(',');
                    for (int i = 0; i < str.Count(); i++)
                    {
                        where += string.Format(num != 0 ? " or " : "");

                        num++;
                        if (item.Replace("[]", "") == "ExpiryDate")
                        {
                            switch (str[i])
                            {
                                case "小于一年":
                                    where += string.Format(" ({0}<='{1}' and {0}>='{2}' )", item.Replace("[]", ""), DateTime.Now.AddYears(1), DateTime.Now);
                                    break;
                                case "1-3年":
                                    where += string.Format(" ({0}>='{1}' and {0}<='{2}' )", item.Replace("[]", ""), DateTime.Now.AddYears(1), DateTime.Now.AddYears(3));
                                    break;
                                case "3-7年":
                                    where += string.Format(" ({0}>='{1}' and {0}<='{2}' )", item.Replace("[]", ""), DateTime.Now.AddYears(3), DateTime.Now.AddYears(7));
                                    break;
                                case "永久":
                                    where += string.Format("({0}='{1}')", item.Replace("[]", ""), new DateTime(1900, 1, 1));
                                    break;
                            }
                        }
                        else if (item.Replace("[]", "") == "SpeculationLevel")
                        {
                            switch (str[i])
                            {
                                case "信貸風險微不足道":
                                    where += string.Format(" {0}='AAA'", item.Replace("[]", ""));
                                    break;
                                case "信貸風險極低":
                                    where += string.Format(" {0} like 'AA_'", item.Replace("[]", ""));
                                    break;
                                case "信貸風險偏低":
                                    where += string.Format(" {0} like 'A_'", item.Replace("[]", ""));
                                    break;
                                case "信貸風險適中":
                                    where += string.Format(" {0} like 'BBB_'", item.Replace("[]", ""));
                                    break;
                                case "信貸風險顯著":
                                    where += string.Format(" {0} like 'BB_'", item.Replace("[]", ""));
                                    break;
                                case "信貸風險偏高":
                                    where += string.Format(" {0} like 'B_'", item.Replace("[]", ""));
                                    break;
                                case "信貸風險極高":
                                    where += string.Format(" {0} like 'CCC_'", item.Replace("[]", ""));
                                    break;

                            }
                        }
                        else if (item.Replace("[]", "") == "ReferenceRate" || item.Replace("[]", "") == "Coupon")
                        {
                            switch (str[i])
                            {
                                case "小于 3%":
                                    where += string.Format(" {0}<'3'", item.Replace("[]", ""));
                                    break;
                                case "3% 到 7%":
                                    where += string.Format("（ {0}>='3' and {0}<=7）", item.Replace("[]", ""));
                                    break;
                                case "7% 到 10%":
                                    where += string.Format("（ {0}>='7' and {0}<=10）", item.Replace("[]", ""));
                                    break;
                                case "大于10%":
                                    where += string.Format(" {0}>10", item.Replace("[]", ""));
                                    break;
                            }
                        }
                        else
                        {
                            where += string.Format(" {0}='{1}'", item.Replace("[]", ""), str[i]);
                        }


                    }
                }

                if (num > 0)
                {
                    where += ")";
                }

                Evan.Model.SysModel.PageModels PageLists = dbOperat.GetPage_2(int.Parse(curPageSize), int.Parse(curpage), where, "Id asc");



                JArray jArray = new JArray();



                foreach (var item in PageLists.Item)
                {

                    JObject jObject = new JObject();
                    jObject["name"] = item.Title;
                    jObject["industry"] = item.Industry;
                    jObject["coupon"] = item.Coupon;
                    jObject["date"] = item.ExpiryDate;
                    jObject["reference"] = item.Reference + " / " + item.Currency;
                    jObject["yields"] = item.ReferenceRate;
                    jArray.Add(jObject);
                }
                res["States"] = true;
                res["data"] = jArray;
                res["curpage"] = PageLists.PageCount;

                JsonResult(context, res);
            }
            catch (System.Threading.ThreadAbortException) { }
            catch (Exception ex)
            {
                res = new JObject();
                res["States"] = false;
                res["Msg"] = ex.Message.ToString();
                JsonResult(context, res);

            }

        }

        private void Message(HttpContext context)
        {
            //获取model
            dynamic model = ContextFormToDynamic(context, ",vcode,jhksrq,jhjzrq,", true, false);
            var form = context.Request.Form;//获取前台表单对象
            model.SubDate = form["jhksrq"] + "-" + form["jhjzrq"];
            model.ClassId = 103;

            //持久化数据
            var newId = new Evan.DataBase.DbOperat("FeedBack").InsertReturnId(model);

            //输出结果
            if (newId > 0)
                JsonResult(context, new Result { States = true, Msg = "提交成功！" });
            else
                JsonResult(context, new Result { States = false, Msg = "提交失败！" });

        }

        private void OnlineMessage(HttpContext context)
        {
            //获取model
            dynamic model = ContextFormToDynamic(context, ",vcode,jhksrq,jhjzrq,token", true, false);
            var form = context.Request.Form;//获取前台表单对象


            string token = form["token"];

            if (string.IsNullOrEmpty(token))
            {
                context.Response.StatusCode = 404;

                context.Response.Write(Evan.Security.SefaTip.ReturnBlueScreen("出错啦", new Exception("输入的字符串不正确")));
                context.Response.End();
            }

            string action = BLL.Utils.GetActionByToken(token);
            if (action != "FormByCustomMessage")
            {
                context.Response.StatusCode = 404;

                context.Response.Write(Evan.Security.SefaTip.ReturnBlueScreen("出错啦", new Exception("输入的字符串不正确")));
                context.Response.End();
            }

            model.SubDate = form["jhksrq"] + "-" + form["jhjzrq"];
            model.ClassId = 19;

            //持久化数据
            var newId = new Evan.DataBase.DbOperat("FeedBack").InsertReturnId(model);

            //输出结果
            if (newId > 0)
                JsonResult(context, new Result { States = true, Msg = "提交成功！" });
            else
                JsonResult(context, new Result { States = false, Msg = "提交失败！" });

        }



        private void CheckFormByAboutJob(HttpContext context)
        {

            var form = context.Request.Form;//获取前台表单对象


            string token = form["token"];

            if (string.IsNullOrEmpty(token))
            {
                JsonResult(context, new Result { States = false, Msg = "未验证到token！" });
            }

            string action = BLL.Utils.GetActionByToken(token);
            if (action != "FormByAboutJob")
            {
                JsonResult(context, new Result { States = false, Msg = "搜索异常，token验证失败！" + action });
            }


            JsonResult(context, new Result { States = true, Msg = "成功！" });



        }


        public static bool sql_inj(string str)
        {
            string inj_str = "'|and|exec|insert|select|delete|update|count|#|*|%|chr|mid|master|truncate|char|declare|;|or|-|+|,";
            string[] inj_stra = inj_str.Split('|');
            for (int i = 0; i < inj_stra.Length; i++)
            {
                if (str.IndexOf(inj_stra[i]) >= 0)
                {
                    return true;
                }
            }
            return false;
        }
    }
}